package com.block.common.annotate.impl;


import com.block.common.annotate.CacheHashEvict;
import com.block.common.service.LogFactory;
import com.block.common.util.SpelUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 设置hash key的缓存
 * 
 * @date 2021/1/27 2:32 下午
 */
@Aspect
@Component
public class CacheHashEvictAspect {
    private Logger logger = LogFactory.getCommLog();

    RedisTemplate redisStrTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate redisStrTemplate) {
        this.redisStrTemplate = redisStrTemplate;
    }

    /**
     * 缓存中设置hashkey
     *
     * @param pjp
     * @param cacheHashEvict
     * @return
     * @throws Throwable
     */
    @Around("@annotation(cacheHashEvict)")
    public Object doAround(ProceedingJoinPoint pjp, CacheHashEvict cacheHashEvict) throws Throwable {
        String key = cacheHashEvict.key();
        String keyName = cacheHashEvict.keyName();

        String hashKey = SpelUtil.getParams(pjp, keyName);
        Object object = pjp.proceed();
        boolean result = redisStrTemplate.opsForHash().hasKey(key, hashKey);
        if(result) {
            Long deleteCount = redisStrTemplate.opsForHash().delete(key, hashKey);
            logger.info("注解删除key:{},hashKey:{},结果:{}",key,hashKey,deleteCount);
        }
        return object;
    }
}
